﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Mvc;

namespace Deixei.Web.Filters
{
    public class ActionLogFilterProvider : IFilterProvider
    {
        private IList<ControllerAction> actions = new List<ControllerAction>();

        public void Add(string areaName, string controllerName, string actionName)
        {
            actions.Add(new ControllerAction()
            {
                AreaName = areaName,
                ControllerName = controllerName,
                ActionName = actionName
            });
        }

        public IEnumerable<Filter> GetFilters(ControllerContext controllerContext, ActionDescriptor actionDescriptor)
        {
            string currentArea = "";
            if (controllerContext.RouteData != null)
            {
                currentArea = controllerContext.RouteData.DataTokens["area"] == null ? "" : (string)controllerContext.RouteData.DataTokens["area"];
            }
            

            foreach (ControllerAction action in actions)
                if (( action.AreaName == currentArea || action.AreaName == "*" )
                    && ( action.ControllerName == actionDescriptor.ControllerDescriptor.ControllerName || action.ControllerName == "*" )
                    && ( action.ActionName == actionDescriptor.ActionName || action.ActionName == "*" ))
                {
                    yield return new Filter(new ActionLogFilterAttribute(), FilterScope.First, null);
                    break;
                }
            yield break;
        }


        internal class ControllerAction
        {
            internal string AreaName
            {
                get;
                set;
            }
            internal string ControllerName
            {
                get;
                set;
            }
            internal string ActionName
            {
                get;
                set;
            }
        }

    }
}
